#define  _CRT_SECURE_NO_WARNINGS 1

//#include<bits/stdc++.h>
#include<iostream>
#include<string>
using namespace std;
const int N = 12;
int dx[] = { -1,-1,0,1,1,1,0,-1 };
int dy[] = { 0,1,1,1,0,-1,-1,-1 };
int n, k;
int a[N][N];
bool b[N][N];
bool c[N][N][N][N];
string ret;
bool dfs(int x, int y)
{
	if (x == n - 1 && y == n - 1)
	{
		return ret.size() == n * n - 1;
	}
	b[x][y] = true;
	for (int i = 0; i < 8; i++)
	{
		int x2 = x + dx[i], y2 = y + dy[i];
		if (x2 < 0 || x2 >= n || y2 < 0 || y2 >= n)
			continue;
		if (b[x2][y2])
			continue;
		if (a[x2][y2] != (a[x][y] + 1) % k)
			continue;
		if (i % 2 && (c[x][y2][x2][y] || c[x2][y][x][y2]))
			continue;
		c[x][y][x2][y2] = true;
		ret += i + '0';
		if (dfs(x2, y2))
			return true;
		ret.pop_back();
		c[x][y][x2][y2] = false;
	}
	b[x][y] = false;
	return false;
}
int main()
{
	cin >> n >> k;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < n; j++)
		{
			cin >> a[i][j];
		}
	}
	if (dfs(0, 0))
		cout << ret;
	else
		cout << "-1";
	return 0;
}